# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description：商品分类路由
"""
from fastapi import APIRouter, HTTPException
from core.Response import base_response
from curd.category import category_add_curd, category_edit_curd
from models.base import Category
from schemas.attr import AttrEditSchemas
from schemas.category import CategoryAddSchemas, CategoryResponseSchemas, CategoryEditSchemas, CategoryOutSchemas, \
    CategorySchemas
from schemas.base import BaseResponse
from typing import Union

category_router = APIRouter(prefix='/category')


@category_router.post('', summary='增加商品分类', response_model=Union[CategoryResponseSchemas, BaseResponse])
async def category_add(post: CategoryAddSchemas):
    try:
        category = await category_add_curd(post)
    except HTTPException as e:
        return base_response(code=str(e).split(':')[0], msg=str(e).split(':')[1])
    except Exception as e:
        return base_response(code=500, msg=f'异常错误！错误原因{e}')
    return base_response(code=200, msg='加商品分类成功！', data=category)


@category_router.delete('/{id}', summary='删除商品分类', response_model=BaseResponse)
async def category_del(id: int):
    category = await Category.get_or_none(id=id)
    if not category:
        return base_response(code=422, msg='该商品分类不存在！')
    await category.delete()
    return base_response(code=200, msg='删除商品分类成功！')


@category_router.put('', summary='编辑商品分类', response_model=Union[CategoryResponseSchemas, BaseResponse])
async def category_edit(post: CategoryEditSchemas):
    try:
        category = await category_edit_curd(post)
    except HTTPException as e:
        return base_response(code=str(e).split(':')[0], msg=str(e).split(':')[1])
    except Exception as e:
        return base_response(code=500, msg=f'异常错误！错误原因{e}')
    return base_response(code=200, msg='编辑商品分类成功！', data=category)


def find_children(categories, parent_id=None):
    return [category for category in categories if category['pid_id'] == parent_id]


def build_tree(categories, level=1):
    if level == 1:
        roots = [category for category in categories if category['level'] == level]
    else:
        roots = [category for category in categories if category['level'] == level - 1]

    def build_node(node, children=None):
        if children is None:
            children = find_children(categories, node['id'])
        if children:
            node['children'] = [build_node(child) for child in children]
        return node

    # 递归构建树
    tree = [build_node(root) for root in roots]
    return tree


@category_router.get('', summary='查询商品分类列表')
async def category_list(level: int = None):
    if level:
        items = await Category.filter(level__lte=level).all()
        items_list = [CategorySchemas(**dict(item)).dict() for item in items]
        tree = build_tree(items_list, level)
    else:
        items = await Category.all()
        items_list = [CategorySchemas(**dict(item)).dict() for item in items]
        tree = build_tree(items_list)

    return base_response(code=200, msg='查询商品分类列表成功！', data=tree)


@category_router.get('/{id}', summary='查询商品分类详情', response_model=Union[CategoryResponseSchemas, BaseResponse])
async def category_detail(id: int, type: str):
    category = await Category.get_or_none(id=id).prefetch_related('attrs')
    if not category:
        return base_response(code=422, msg='该商品分类不存在！')

    attrs = [AttrEditSchemas(**dict(attr), type=dict(attr)['_type']) for attr in category.attrs]
    if type not in ['static', 'dynamic']:
        return base_response(code=422, msg='type参数错误！')
    if type == 'static':
        attrs = [attr for attr in attrs if attr.type == 'static']
    else:
        attrs = [attr for attr in attrs if attr.type == 'dynamic']

    return base_response(code=200, msg='查询商品分类详情成功！', data=CategoryOutSchemas(**dict(category), attrs=attrs))
